<template>
  <el-container class="h-full">
    <el-aside class="w-64 border-0 border-r border-solid border-gray-200">
      <VisitorList :list="visitorData.list" v-model="visitorData.selectedId" />
    </el-aside>
    <el-container direction="vertical">
      <template v-if="visitorData.selectedId">
        <el-header class="h-auto min-h-[60px] py-[14px]">
          <TopToolbar />
        </el-header>
        <el-main class="p-0 h-0">
          <MessageList
            :side="UserTypeEnum.SERVICE"
            :list="messageData.list"
            @withdraw="handleWithDraw"
          />
        </el-main>
        <el-footer class="p-0 h-auto">
          <MessageEditor @send="handleSend" />
        </el-footer>
      </template>
    </el-container>
    <el-aside class="w-64 border-0 border-l border-solid border-gray-200">
      <VisitorInfo />
    </el-aside>
  </el-container>
</template>

<script setup lang="ts">
import VisitorList from '@/manager/components/VisitorList.vue'
import TopToolbar from '@/manager/components/TopToolbar.vue'
import MessageList from '@/common/components/ChatMessageList.vue'
import MessageEditor from '@/manager/components/MessageEditor.vue'
import VisitorInfo from '@/manager/components/ExpansionPanel.vue'
import { reactive, watch } from 'vue'
import { requestMessageData, getVisitorList } from '@/manager/api'
import { useLoginData } from '@/manager/store'
import bridge from '@/common/bridge'
import { ReceiveMessageType, UserTypeEnum } from '@/common/constants'

const { loginData } = useLoginData()

const handleSend = (content: string) => {
  bridge.sendSingleMessage({
    fromUserId: loginData.userId,
    toUserId: visitorData.selectedId,
    serviceId: loginData.userId,
    visitorId: visitorData.selectedId,
    content
  })
  messageData.list.push({
    key: Date.now().toString(),
    from: UserTypeEnum.SERVICE,
    id: loginData.userId,
    name: '',
    avatar: '',
    content,
    read: false,
    time: Date.now()
  })
}

const handleWithDraw = async () => {
  // @ts-ignore
  await ElMessageBox.confirm('即將測回一條訊息請確認...', '友情提示')
}

const visitorData = reactive({
  list: [],
  selectedId: ''
})

getVisitorList(loginData.userId).then((res) => {
  visitorData.list = res.data.list
})

const messageData = reactive({
  list: []
})

watch(
  () => visitorData.selectedId,
  async () => {
    const res = await requestMessageData({
      serviceId: loginData.userId,
      visitorId: visitorData.selectedId,
      pageNum: 1
    })

    messageData.list = res.list
  }
)

bridge.receiveMessage(ReceiveMessageType.SINGLE_SENDING, (data) => {
  messageData.list.push({
    key: Date.now().toString(),
    from: UserTypeEnum.VISITOR,
    id: data.fromUserId,
    name: '',
    avatar: '',
    content: data.content,
    read: false,
    time: Date.now()
  })
})
</script>

<style scoped></style>
